package com.btpn.custody.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.btpn.custody.dao.IRegion;
import com.btpn.custody.entity.Region;

@Repository("regionDaoHibernate")
public class RegionDAO implements IRegion {

	protected HibernateTemplate template = null;
	
	@Autowired @Required
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	@Override
	public Region get(Long id) {
		return template.get(Region.class, id);
	}
	
	@Override
	public List<Region> getAll() {
		return template.loadAll(Region.class);
	}
	
	@Override
	public Integer getCount() {
		return Integer.valueOf(getAll().size());
	}
	
	@Override
	public Serializable create(Region region) {
		return template.save(region);
	}

	@Override
	public void createOrUpdate(Region region) {
		template.saveOrUpdate(region);
	}
	
	@Override
	public void update(Region region) {
		template.update(region);
	}

	@Override
	public void delete(Long id) {
		template.delete(get(id));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Region getByName(String regionName) {
		List<Region> result = template.findByNamedQueryAndNamedParam(Region.NQ__FIND__BY__NAME, "regionName", regionName);
		
		if (result.size()>0) {
			return result.get(0);
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Region getByCode(String regionCode) {
		List<Region> result = template.findByNamedQueryAndNamedParam(Region.NQ__FIND__BY__CODE, "regionCode", regionCode);
		
		if (result.size()>0) {
			return result.get(0);
		} else {
			return null;
		}
	}
}